#include "bdd.h"

void
pouf (subbase * b)
{
  subbase *s, *par = NULL;
  row *r;
  int dec = 0, t, flag = 0;

  if (!b)
    return;
  s = b;

  while (1)
    {
      if (s)
	{
	  flag = 0;
	  for (t = 0; t < dec; t++)
	    printf ("\t");
	  printf ("subbase: %s\n", s->ident);

	  for (r = s->rows; r; r = r->next)
	    {
	      for (t = 0; t < dec+1; t++)
		printf ("\t");
	      printf ("row: %s : %s\n", r->ident, r->val);
	    }

	  par = s;
	  s = s->enfant;
	  dec++;
	}
      else
	{
	  dec--;
	  s = par;
	  if (!s || s == b)
	    break;
	  par = s->parent;
	  s = s->next;
	}
    }
}

/*
      else
	{
	  if (!flag)
	    dec--;
	  s = par;
	  if (s->next)
	    s = s->next;
	  else
	    {
	      dec--;
	      flag = 1;
	      s = s->parent;
	      if (!s || s == b)
		break;
	      par = s;
	      s = s->next;
	    }
	}
*/


char *
dup_low_string (char *str)
{
  int dec = 'A' - 'a';
  char *r, *x = malloc (strlen (str) + 1);
  r = x;
  while (*str)
    {
      if (*str >= 'A' && *str <= 'Z')
	*r = *str - dec;
      else
	*r = *str;
      str++;
      r++;
    }
  *r = 0;
  return x;
}


void
low_string (char *str)
{
  int dec = 'A' - 'a';
  while (*str)
    {
      if (*str >= 'A' && *str <= 'Z')
	*str -= dec;
      str++;
    }
}

byte
valid_string (char *str)
{
  char *p;
  for (p = str; *p; p++)
    if (*p == 0x1C || *p == 0x1D || *p == 0x1E || *p == 0x1F)
      return 0;
  return 1;
}

byte
valid_basename (char *str)
{
  char *p;
  if (strstr (str, ".."))
    return 0;

  for (p = str; *p; p++)
    if (*p == '\\' || *p == '/')
      return 0;
  return (valid_string (str));
}

void
clean_session_row (row * p)
{
  uint a;
  for (a = 1; a < sess_top; a++)
    if (sess_tab[a] && sess_tab[a]->rowptr == p)
      sess_tab[a]->rowptr = NULL;
}

void
clean_session_subbase (subbase * p)
{
  uint a;
  for (a = 1; a < sess_top; a++)
    if (sess_tab[a] && sess_tab[a]->subptr == p)
      sess_tab[a]->subptr = NULL;
}

void
clean_session_base (subbase * p)
{
  uint a;
  for (a = 1; a < sess_top; a++)
    if (sess_tab[a] && sess_tab[a]->baseptr == p)
      {
	sess_tab[a]->baseptr = NULL;
	sess_tab[a]->rootptr = NULL;
      }
}

byte
session_on_base (subbase * p, uint s)
{
  uint sid;
  for (sid = 1; sid < sess_top; sid++)
    if (sid != s && sess_tab[sid] && sess_tab[sid]->baseptr == p)
      return 1;
  return 0;
}

char **
str_to_tab (char *buffer, char delim, int *nb)
{
  char **argu;
  char *runner = buffer;
  unsigned int cc = 0, n;
  argu = (char **) malloc (sizeof (char *));

  while (*buffer)
    {
      for (; *buffer != delim && *buffer; buffer++);
      n = buffer - runner;
      argu = (char **) realloc (argu, (cc + 1) * sizeof (char *));
      *(argu + cc) = (char *) malloc (n + 1);

      strncpy (*(argu + cc), runner, n);
      *(argu[cc] + n) = 0;
      cc++;

      while (*buffer == delim)
	buffer++;
      runner = buffer;
    }
  *nb = cc;
  return (argu);
}
